import { Layout, Menu, MenuProps } from "antd";
import { useLocation, useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
import { getRouteByJson } from "@/api/routeApi.ts";
import { routeFilter } from "@/router/index.ts";
import { connect } from "react-redux";
import { changeUserAction } from "@/redux/module/user.ts";
import { changeValueAction } from "@/redux/module/breadcurmb.ts";

const { Sider } = Layout;

import "./index.scss";

const Sider_Antd = ({ user, changeValue }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const [routes, setRoutes]: any = useState([]);
  const [activeKey, setActiveKey] = useState("轮播图");
  const [defaultOpenKeys, setDefaultOpenKeys] = useState([
    "首页",
    "学习",
    "好玩",
    "echarts",
    "css",
  ]);
  const setMenuItem = (arr) => {
    const result: any = [];
    arr.forEach((item) => {
      const obj: any = {
        label: item.label,
        key: item.label,
        path: item.path,
        children: [],
      };

      if (item.children && item.children.length > 0) {
        obj.children = setMenuItem(item.children);
      } else {
        delete obj.children;
      }
      result.push(obj);
    });
    return result;
  };

  useEffect(() => {
    getRouteByJson().then((res) => {
      const filterRouteList: any = routeFilter(res, user);
      setRoutes(setMenuItem(filterRouteList));
      setActiveKey(location.state.title);
      changeValue(location.state.crumb);
    });
  }, []);

  const onMenuClick: MenuProps["onClick"] = ({ item, key, keyPath }: any) => {
    changeValue(keyPath.reverse());
    setActiveKey(key);
    navigate(item.props.path, {
      state: {
        title: key,
        crumb: keyPath,
      },
    });
  };

  return (
    <Sider
      className="container frostedGlass"
      style={{
        overflow: "auto",
        maxWidth: "100px",
        height: "calc(100vh - 120px)",
        marginRight: "10px",
      }}
    >
      <Menu
        mode="inline"
        defaultOpenKeys={defaultOpenKeys}
        selectedKeys={[activeKey]}
        style={{ height: "100%" }}
        onClick={onMenuClick}
        className="menu"
        items={routes}
      ></Menu>
    </Sider>
  );
};
export default connect(
  (state: any) => ({
    user: state.user.userLevel,
  }),
  (dispatch) => {
    return {
      changeUser: (data) => {
        dispatch(changeUserAction(data));
      },
      changeValue: (data) => {
        dispatch(changeValueAction(data));
      },
    };
  },
)(Sider_Antd);
